<?php

class TestUserSessions extends UnitTestCase {

    function testFactory() {
        $user_id = 1;
        $session = UserAuthSession::factory($user_id);

        //$this->dump($session);
        if (!$this->assertIsA($session, 'UserAuthSession', "UserAuthSession::factory() should return a UserAuthSession instance")) {
            return false;
        }
        $this->assertEqual($session->getUserId(), $user_id, "with a correct user_id");
        $this->assertTrue($session->isValid(), "session->isValid() should return true");
        $now = DatetimeBean::now();
        $this->assertEqual($session->start_date, $now, "start date should be now %s");
        $this->assertFalse($session->isClosed(), "session->isClosed() should return false");
        // now close and check
        $this->assertTrue($session->close(), "session->close() should return true");
        $this->assertTrue($session->isClosed(), "and then session->isClosed() should return true");
        $this->assertTrue($session->isValid(), "But a closed session still return true for isValid()");
    }

    function testCycle() {
        $user_id = 36;
        $S = $this->_getSessions();
        $new = $S->create($user_id);
        $this->assertIsA($new, 'UserAuthSession', "UserAuthSessions::create($user_id) should return a new saved session");
        $this->assertTrue($new->isValid(), "ssesion should be valid");
        $this->assertFalse($new->closed(), "and not closed");
        $id = $new->id;
        // now we get back the session to check it has been saved
        $copy = $S->get($id);
        $this->assertEqual($new, $copy, "and get($id) should get back the session %s");

        // now we close the session
        $this->assertTrue($S->close($new), "UserAuthSessions::close() should return true");
        $this->assertTrue($new->isClosed(), "and update session so that its closed() method return true");
    }

    /**
     * @return UserAuthSessions
     */
    function _getSessions() {
        $admin = Webappkit::getKit('webappkit.admin');
        return new UserAuthSessions($admin->getTestsDbLink());
    }
}